import datetime
from werkzeug.security import generate_password_hash, check_password_hash

from .init_sqlalchemy import db


class Base(db.Model):
    __abstract__ = True  # 将类标记为抽象基类

    def to_str(self):
        return '(User: name: {}, pass_hash: {})'.format(self.name, self.password)

    def to_dict(self):
        # 字典推导式，过滤掉密码
        data = {column.name: getattr(self, column.name) for column in self.__table__.columns if
                column.name != 'password'}
        for key, value in data.items():
            if isinstance(value, datetime.datetime):
                data[key] = value.strftime('%Y-%m-%d %H:%M:%S')
        return data

    def keys(self):
        return self.fields

    def __getitem__(self, item):
        return getattr(self, item)


class UserBase(Base):
    __abstract__ = True  # 将类标记为抽象基类

    pass_word = db.Column(db.String(12), comment='密码')

    @property
    def pass_word(self) -> None:
        pass

    @pass_word.setter
    def pass_word(self, pass_word):
        self.password = generate_password_hash(pass_word)

    def validate_password(self, password):
        print('hash:' + self.password + ',pass:' + password)
        return check_password_hash(self.password, password)